define(function(require, exports, module)
{
  var $ = require("$");
  var bootbox = require("bootbox");
  var dtUtil = require('datatableutil');
  require("bootstrap_commonrequire");
  require("moment");
  require('daterangepicker.css');
  require('bootstrap-daterangepicker');
  require('select2.css');
  require('select2');
  exports.init = function(param)
  {

    $(document).ready(function()
    {

      // 加载自定义模板-条件区域
      var template = require("./recharge.tpl");
      var Widget = require("widget");
      var Component = Widget.extend(
      {
        template : template
      });
      new Component(
      {
        renderTo : "seachdiv"
      });

      // 初始化充值类型
      $("#select_type").select2({
        allowClear : true,
        multiple : false,
        type : "text",
        style : "width:50%",
        placeholder : "充值类型",
        data : [ {
          id : 'app',
          text : "APP充值"
        }, {
          id : 'company',
          text : "企业充值"
        }/*, {
          id : 'persion',
          text : "用户个人充值"
        }*/
        ]
      });
      // 绑定isv名称下拉列表
      $.ajax(
       {
           type : "POST",
           dataType : "json",
           url : "/user/queryIsv.do",//GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,// wp.huang
           async : false,
           success : function(data)
           {
            $("#select_isvid").select2({
              placeholder : "请选择ISV名称",
              allowClear: true,
                  data: data
                });
           },
           error : function(data)
           {
               bootbox.alertTimeout('初始化ISV名称数据失败！');
           }
       });
      
      // 绑定APP下拉列表
      $("#select_appid").select2({
          placeholder: "请选择APP",
           allowClear: true,
                 ajax: {
                   url: "/condition/getAppName.do",
                   dataType: 'json',
                   delay: 250,
                   data: function (term, pageNo) {
                     return {
                       q: " a.name like '%"+term+"%' ", // search term
                       isvid: $("#isvid").val(),
                       size: 25,
                       start: (pageNo-1)*25
                     };
                   },
                   results: function (data, pageNo) {
                     var dataObj = eval(data);
                     return {results:dataObj};
                   },
                   cache: true
                 }
        });
      
      // 绑定企业下拉列表
      $("#select_companyid").select2({
          placeholder: "请选择企业",
           allowClear: true,
                 ajax: {
                   url: "/condition/getCompanyName.do",
                   dataType: 'json',
                   delay: 250,
                   data: function (term, pageNo) {
                     return {
                       q: " c.name like '%"+term+"%' ", // search term
                       appid: $("#appid").val(),
                       size: 25,
                       start: (pageNo-1)*25
                     };
                   },
                   results: function (data, pageNo) {
                     var dataObj = eval(data);
                     return {results:dataObj};
                   },
                   cache: true
                 }
        });
      
      // 充值途径 
      $("#select_rechargetype").select2({
        allowClear : true,
        multiple : false,
        type : "text",
        style : "width:50%",
        placeholder: "请选择充值途径 ",
        data : [ {
          id : 0,
          text : "对公转账"
        }, {
          id : 1,
          text : "调试赠送"
        }, {
          id : 2,
          text : "第三方平台充值"
        }, {
          id : 3,
          text : "同步信息赠送"
        } ]
      });
      
      //审核状态
      var typeList = [{"id":2,"text":"待审核"},{"id":1,"text":"通过"},{"id":3,"text":"未通过"}];
      $('#select_auditingstatus').select2({
          placeholder: "请选择充值状态",
          allowClear: true,
          data: typeList
      });
      $('#select_auditingstatus').select2('val',2);
      

      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
      label : "充值时间"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });
      
      var Table = require("table");
      new Table(
          {
            attrs :
            {
              id : "rechargeauditing",
              isHovered : false,
              isStriped : true,
              isBordered : false
            },
            renderTo : param.divWrapperId
          });
      var rechargeauditing = $('#rechargeauditing').dataTable(
      {
        "sDom" : "<'hidden'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" :
        {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        "scrollX" : true,
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bInfo" : true,
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT,
        "sAjaxSource" : param.ajaxUrl, // 数据源
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings)
        {
          var queryparam = dtUtil.convert_aoData(aoData);
          var type = $('#select_type').val();
          var businessnum = $('#select_businessnum').val();
          var startTime = "";
          var endTime = "";
          var isvid = $('#select_isvid').val();
          var appid = $('#select_appid').val();
          var companyid = $('#select_companyid').val();
          var rechargetype = $('#select_rechargetype').val();
          var auditingstatus = $('#select_auditingstatus').val();
          // 获取时间查询参数
          var daterange = daterangeCom.getPickerRange();
          if (daterange)
          {
            var daterange = daterange.split("/");
            startTime = daterange[0]+ " 00:00:00";
            endTime = daterange[1]+ " 23:59:59";
          }
          
          //查询条件参数
          var data = {
              "start": queryparam.start,
              "size": queryparam.size,
              "type":type,
              "businessnum":businessnum,
              "startTime":startTime,
              "endTime":endTime,
              "isvid":isvid,
              "appid":appid,
              "companyid":companyid,
              "rechargetype":rechargetype,
              "auditingstatus":auditingstatus
          };
          // 添加自己的额外参数
          oSettings.jqXHR = $.ajax(
          {
            "dataType" : 'json',
            "contentType" : "application/json;charset=UTF-8",
            "type" : "GET",
            "url" : sSource,
            "data" : data, // 将请求数据转换为后台要求的JSON格式
            "success" : function(json)
            {
              dtUtil.successCallback(json, aoData, fnCallback);
            }
          });
         },
         "aaSorting" : [[0, "desc"]],
        "aoColumns" : [
        /*{
          "sTitle" : '<input class="only-checkbox" type="checkbox" id="checkall">',
          "bSortable" : false,
          "mData" : "id",
          "mRender" : function(data, type, full)
          {
            //将body中的dataArray值赋给dataArray
            var dataArray = $("body").data("dataArray");
            // 判断data是否在dataArray中
            if ($.inArray(data, dataArray) > -1)
              return '<input class="only-checkbox tableCheckbox" type="checkbox" checked>';
            else
              return '<input class="only-checkbox tableCheckbox" type="checkbox">';
          }
        },*/
        {
          "bVisible" : false,
          "mData" : "isvid"
        },{
          "bVisible" : false,
          "mData" : "appid"
        },{
          "bVisible" : false,
          "mData" : "companyid"
        },{
          "sTitle" : "充值类型",
          "bSortable" : false,
          "mData" : "type",
          "mRender" : function(data, type, full)
          {
            
            /*if (data == 'app')
              return "APP充值";
            else if(data == 'company')
              return "企业充值";*/
            
            if (data == 0)
              return "对公转账";
            else if (data == 1)
              return "调试赠送";
            else if (data == 2)
              return "第三方平台充值";
            else if (data == 3)
              return "同步信息赠送";
          
          }
        },
        {
          "sTitle" : "ISV",
          "bSortable" : false,
          "mData" : "isvname"
        },
        {
          "sTitle" : "APP",
          "bSortable" : false,
          "mData" : "appname"
        },{
          "sTitle" : "企业",
          "bSortable" : false,
          "mData" : "companyname"
        },
        {
          "sTitle" : "充值途径",
          "bSortable" : false,
          "mData" : "rechargetype",
          "mRender" : function(data, type, full)
          {
            if (data == 0)
              return "对公转账";
            else if (data == 1)
              return "调试赠送";
            else if (data == 2)
              return "第三方平台充值";
            else if (data == 3)
              return "同步信息赠送";
          }
        },
        {
          "sTitle" : "业务单号",
          "bSortable" : false,
          "mData" : "businessnum"
        },
        {
          "sTitle" : "充值时间",
          "bSortable" : false,
          "mData" : "rechargetime"
        },{
          "sTitle" : "金额",
          "bSortable" : false,
          "mData" : "amount",
          "sWidth": "6%"
        },
        {
          "sTitle" : "审核人",
          "bSortable" : false,
          "mData" : "auditor"
        },
        {
          "sTitle" : "充值状态",
          "bSortable" : false,
          "mData" : "rechargestatus",
          "mRender" : function(data, type, full)
          {
            if (data == 2)
              return "待审核";
            if (data == 1)
              return "审核通过";
            if (data == 3)
              return "未通过";
          }
        },
        {
          "sTitle" : "备注",
          "bSortable" : false,
          "mData" : "remarks"
        },
        {
          "sTitle" : "操作",
          "bSortable" : false,
          "mData" : "rechargestatus",
          "mRender" : function(data, type, full)
          {
              var ret = '<div class="btn-group" style="margin-top: 8px;">';
              if(data==2)
                ret += '<a href="javascript:void(0);" class="btn icon-edit-sign contrast" title="审核"></a>';
              else
                ret += '<a href="javascript:void(0);" class="btn icon-edit-sign contrast disabled" title="取消审核"></a>';
              return ret += '</div>';
     
          }
        }],
        "fnDrawCallback" : function(oSettings)
        {
          var checkboxs = $(".tableCheckbox");
          for (var i = 0; i < checkboxs.length; i++)
          {
            var checkbox = checkboxs[i];
            var rowData = rechargeauditing.fnGetData(i);
            var rechargestatus = rowData.auditingstatus;
            if (rechargestatus ==1 ||rechargestatus == 3)
            {
              $(checkbox).attr("disabled", 'true');
              $(checkbox).removeAttr("checked");
            }
          }
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });
      //批量审批
      /*$("#creatbtn").on("click", function()
      {
        var dataArray = $("body").data("dataArray");
        if (!dataArray || dataArray.length <= 0)
        {
          bootbox.alert("请选择要审批的记录！！！");
          return false;
        }
        auditingaction(dataArray);
      });*/
      //审批
      $("#rechargeauditing tbody").on("click", "tr>td>div>a.icon-edit-sign", function(e)
      {
        e = e || window.event;
        var o = e.target || e.srcElement;
        if (o.title=="取消审核") return;
        var rowNode = this.parentNode.parentNode.parentNode;
        var rowData = rechargeauditing.fnGetData(rowNode); 
        auditingaction(rowData.id+":"+rowData.type);
      });
      // 全选全消
      $("#rechargeauditing thead").on("click", "#checkall", function(e)
      {
        var check = $(this).attr("checked");
        var checkboxs = $(".tableCheckbox");
        var dataArray = $("body").data("dataArray");
        if (!dataArray)
          dataArray = new Array();
        for (var i = 0; i < checkboxs.length; i++)
        {
          var checkbox = checkboxs[i];
          var rowData = rechargeauditing.fnGetData(i);
          if (check == "checked")
          {
            if(rowData.rechargestatus ==2)
            {
                $(checkbox).attr("checked", 'true');
                dataArray.push(rowData.id+":"+rowData.type);
            }
          }
          else
          {
            if(rowData.rechargestatus ==2)
            {
              $(checkbox).removeAttr("checked");
              dataArray.splice($.inArray(rowData.id+":"+rowData.type, dataArray), 1);
            }
          }
        }
        $("body").data("dataArray", dataArray);
      });
      //复选框
      $("#rechargeauditing tbody").on("click", " tr td .tableCheckbox", function()
      {
        var rowNode = this.parentNode.parentNode;
        var rowData = rechargeauditing.fnGetData(rowNode);
        var check = $(this).attr("checked");
        var dataArray = $("body").data("dataArray");
        if (!dataArray)
          dataArray = new Array();
        if (check)
          dataArray.push(rowData.id+":"+rowData.type);
        else
          dataArray.splice($.inArray(rowData.idv, dataArray), 1);

        $("body").data("dataArray", dataArray);
      });
      
      $('#querybtn').on('click', function()
      {
        var dataArray = $("body").data("dataArray");
        if (dataArray)
          $("body").data("dataArray", null);
        rechargeauditing.fnFilter();
        return false;
      });
      //重置
      $('#restbtn').on('click', function()
      {
        $('#select_type').select2("val", "");
        $('#select_businessnum').val("");
        daterangeCom.clearInput();
        $('#select_isvid').select2("val", "");
        $('#select_appid').select2("val", "");
        $('#select_companyid').select2("val", "");
        $('#select_rechargetype').select2("val", "");
        $('#select_auditingstatus').select2('val',0);
        rechargeauditing.fnFilter("");
        return false;
      });
    });
  };
  
  
  
  
  // 审核弹出窗口
  var auditingaction = function(ids)
  {
    var auditing = require("./auditing");
    if ($("#auditingid").length <= 0)
      $("body").append("<div id='auditingid'></div>");
    auditing.init(
    {
      "title" : "充值审批",
      "renderTo" : "auditingid",
      "passaction" : function(text)
      {
        var auditMsg = $("#auditing_text").val();
        var data = "id=" + ids + "&auditMsg=" + auditMsg;
        $.ajax(
        {
          url : "/isv/doAudit.do", //GLOBAL.URL.ADMIN_LICENSEAUDITING + "0.do",
          dataType : "json",
          type : "POST",
          data : "status=1&" + data,
          success : function(resdata)
          {
            if(resdata.flag == '000000'){
              $("body").data("dataArray", null);
              $("#rechargeauditing").dataTable().fnFilter();                    
            } else {
              oauth2Relogin();                    
            }
          }
        });
      },
      "backaction" : function(text)
      {
        var auditMsg = $("#auditing_text").val();
        var data = "id=" + ids + "&auditMsg=" + auditMsg;
        $.ajax(
        {
          url : "/isv/doAudit.do", //GLOBAL.URL.ADMIN_LICENSEAUDITING + "4.do",
          dataType : "json",
          type : "POST",
          data : "status=3&" + data,
          success : function(resdata)
          {
            if(resdata.flag == '000000'){
              $("body").data("dataArray", null);
              $("#rechargeauditing").dataTable().fnFilter();                   
            } else {
              oauth2Relogin();                    
            }
          }
        });
      }
    });
  };
});
